<template>
  <base-page-view :class-name="classPage" :show-to-top="false">
    <base-nav title="购物车" :refresh-flag="refreshFlag">
      <view slot="left" class="editTitle" @click="editCaryState = !editCaryState">
        <view v-if="cartList.length>0">
          {{ editCaryState ? '完成' : '编辑' }}
        </view>
      </view>
    </base-nav>
    <view class="cart_content">
      <view v-if="!cartList.length && showBlur" class="emptyBox">
        <b-image src="/static/images/empty/empty_cart.png" class="empty_image" :is-asset="true" />
        <view class="decorate">
          亲，你的购物车还没有宝贝哦～~
        </view>
        <view class="toHome" @click="$navigateTo('/pages/home/index','','switchTab')">
          去逛逛
        </view>
      </view>
      <view v-if="cartList.length" class="shoppingCart">
        <view class="product-all">
          <view v-for="(parItem, parIndex) in cartList" :key="parIndex" class="cartItem">
            <view v-if="parItem.type === 4" class="title">
              <view class="titleLeft">{{ parItem.title }}</view>
              <view class="titleRight" @click="deleteAll()">
                <image src="/static/images/cart/icon_trash.png" />
                <text class="o-span">全部清空</text>
              </view>
            </view>
            <view v-if="parItem.full_cut_id" class="full-cut-icon" @click="lookFullCutShop(parItem)">
              <view class="full-cut-tag">{{ parItem.full_cut_tag }}</view>
              <view v-if="parItem.full_cut_id" class="full-cut-content">
                <rich-text :nodes="replaceHtmlNum(parItem)" />
                <!-- {{ replaceHtmlNum(parItem.full_cut_msg) }} -->
              </view>
              <view class="full-cut-btn">去凑单<image src="/static/images/cart/red_arr_r_ico.png" class="red-icon" /></view>
            </view>
            <view v-for="(item, index) in parItem.shopping_item_list" :key="index">
              <uni-swipe-action>
                <uni-swipe-action-item :options="options" :auto-close="true" :disabled="true" @click="swipeClick($event,item)">
                  <view style="width: 100%;" :class="{'bor-bot': item.pack_goods && (item.pack_goods.pack_list.length > 0 || item.pack_goods.present_list.length > 0)}">
                    <view class="product-info">
                      <view class="product-check" @click="addToSelected(item, parItem)">
                        <text :class="{'checked': selectList.indexOf(item) > -1, 'disable': parItem.type === 4}" class="o-span"></text>
                      </view>
                      <view class="product-box" @click="toGoodsDetail(item)">
                        <div class="product-img">
                          <image :src="item.pic" class="img-item" />
                          <div v-if="item.status===4" class="maskIm">
                            <image src="/static/images/cart/img_Soldout.png" class="masImg" />
                          </div>
                          <div v-if="item.status===5" class="maskIm">
                            <image src="/static/images/cart/img_SoldDown.png" class="masImg" />
                          </div>
                        </div>
                        <view class="product-intro">
                          <view>
                            <view class="goodsTitle">
                              <text v-if="item.type === 2" class="o-span" :class="{'blueTitle': item.type !== 2 && item.is_self !== 1}">
                                {{ item.type === 2 ? '套餐' : item.is_self === 1 ? '自营' : '商家' }}
                              </text>
                              {{ item.title }}
                            </view>
                            <view class="proper">
                              <text class="o-span">{{ trimSize(item.properties_name) }}</text>
                            </view>
                          </view>
                          <view v-if="parItem.type!==4" class="price">
                            ¥{{ item.from_type === 9 ? item[getShowPrice(user_info)] :item.vip_price.toFixed(2) }}
                          </view>
                        </view>
                      </view>
                      <div v-if="parItem.type !== 4" class="clicks">
                        <!-- baseStepper -->
                        <base-stepper :value="item.num" :min="1" :max="999" :size="34" :border-radius="4" @change="cartNumChange($event,item)"></base-stepper>
                      </div>
                    </view>
                  </view>
                </uni-swipe-action-item>
              </uni-swipe-action>
              <!-- 套餐和赠品开始 -->
              <view v-for="(spitem, spindex) in item.pack_goods" :key="spindex">
                <view v-for="(sitem, sindex) in spitem" :key="sindex">
                  <block v-if="spitem.length">
                    <view class="product-info">
                      <view class="product-check"></view>
                      <view class="product-box" @click="toGoodsDetail(item)">
                        <view class="product-img">
                          <image :src="sitem.pic" class="img-item" />
                          <view v-if="(item.status === 4)" class="maskIm">
                            <image src="/static/images/cart/img_Soldout.png" class="masImg" />
                          </view>
                          <view v-if="(item.status === 5)" class="maskIm">
                            <image src="/static/images/cart/img_SoldDown.png" class="masImg" />
                          </view>
                        </view>
                        <view class="product-intro">
                          <view>
                            <view class="goodsTitle">
                              <text v-if="spindex === 'present_list'" class="o-span">赠品</text> {{ sitem.title }}
                            </view>
                            <view class="proper">
                              <text class="o-span">{{ trimSize(sitem.properties_name) }}</text>
                            </view>
                          </view>
                          <view v-if="parItem.type !== 4" class="bottom-price">
                            <view :class="{'deletePrice': true}">
                              ¥{{ sitem.vip_price.toFixed(2) }}
                            </view>
                            <view class="num">
                              ×{{ item.num }}
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </block>
                </view>
              </view>
              <!-- 套餐和赠品结束 -->
            </view>
          </view>
        </view>
      </view>
      <view v-if="showBlur" class="moreProduct">
        <view class="decotate">
          <view class="decorete_text">猜你喜欢</view>
          <view class="decorete_text_en">ALL THE GOODS</view>
        </view>
        <likeList ref="likeGoodsList" image-width="360rpx" image-radius="0" />
      </view>
    </view>
    <!-- 结算底部 -->
    <view v-if="cartList.length>0" class="bottomFix">
      <view class="bottom-container">
        <view class="select-all" @click="selectedAll()">
          <text :class="{'checked': checkedImage()}" class="o-span"></text>
          全选
        </view>
        <view class="bottom-right">
          <view v-if="!editCaryState" class="rButton" :class="{'blur': !selectListLength}" @click="toOrderCheck()">结算{{ selectListLength? `(${selectListLength})` : '' }}</view>
          <view v-if="editCaryState" class="rButton" :class="{'blur': !selectListLength}" @click="deleteCartArray(selectList)">删除{{ selectListLength? `(${selectListLength})` : '' }}</view>
          <view v-if="!editCaryState" class="lPrice">
            <text>合计:</text>
            <text class="totalPrice priceSign">{{ totalPrice.toFixed(2) }}</text>
          </view>
        </view>
      </view>
    </view>
    <confirm-popup ref="confirm" />
  </base-page-view>
</template>

<script>
// import store from '@/stores/index'
import uniSwipeAction from '@/components/swipeAction/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '@/components/swipeAction/uni-swipe-action-item/uni-swipe-action-item.vue'
import baseStepper from '@/components/base/base-stepper.vue'
import baseNav from '@/components/base/base-nav.vue'
import likeList from '@/components/likeGoodsList/index'
import { toGoods } from '@/utils/navigateTo'
import { debounce } from '@/utils/tools'
import confirmPopup from '@/components/confirmPopup/index'
import './index.scss'
export default {
  components: {
    uniSwipeAction,
    uniSwipeActionItem,
    baseStepper,
    baseNav,
    likeList,
    confirmPopup
  },
  data() {
    return {
      hasFullCut: false,
      fullCutMoney: 0,
      goodsList: [],
      cartList: [],
      selectList: [],
      showTips: false,
      editCaryState: false,
      showBlur: false,
      showAll: false,
      needCoach: 0,
      options: [
        {
          text: '收藏',
          style: {
            backgroundColor: 'rgb(255, 117, 159)'
          },
          icon: '/static/images/cart/cart_collect.png'
        }, {
          text: '删除',
          style: {
            backgroundColor: 'rgb(200, 199, 204)'
          },
          icon: '/static/images/cart/cart_delete.png'
        }
      ],
      user_info: '',
      refreshFlag: false
    }
  },
  computed: {
    replaceHtmlNum() {
      return function(item) {
        if (!item.full_cut_list) {
          return ''
        }
        const arr = item.full_cut_list
        // const list = []
        // let cache = {}
        let hasSelected = false
        let nowTotal = 0
        let string = ''
        let moneyLevel = false
        // let currentLevel = 0
        let moneyLeft = 0
        let firstWord = ''
        let cutMoney = 0
        let stringWord = ''
        item.shopping_item_list.map(item => {
          if (item.checked) {
            // nowTotal += item.num * (item.from_type === 9 ? item[this.getShowPrice(this.user_info)] : item.vip_price.toFixed(2))
            nowTotal += (item.num * item.vip_price)
            hasSelected = true
          }
        })
        // 如果有选中的商品
        if (hasSelected) {
          arr.forEach((i, k) => {
            // 如果已经定位到了总价区间
            if (moneyLevel) { return }
            // 如果在此价位
            if (nowTotal < i.full) {
              moneyLevel = true
              // currentLevel = i.full
              moneyLeft = this.accSub(i.full, nowTotal)
              // 中间
              if (k <= 0) {
                firstWord = '购满<span style="color:#CF152F">' + i.full + '</span>元可减<span style="color:#CF152F">' + i.cut + '</span>元，还差<span style="color:#CF152F">' + moneyLeft + '</span>元'
              } else if (k > 0 && k <= arr.length - 1) {
                cutMoney = arr[k - 1].cut
                firstWord = '购满<span style="color:#CF152F">' + arr[k - 1].full + '</span>元已减<span style="color:#CF152F">' + arr[k - 1].cut + '</span>元，满<span style="color:#CF152F">' + i.full + '</span>元可减<span style="color:#CF152F">' + i.cut + '</span>元'
              }
            } else if (nowTotal > i.full && k === arr.length - 1) {
              cutMoney = i.cut
              moneyLevel = true
              firstWord = '购满<span style="color:#CF152F">' + i.full + '</span>元已减<span style="color:#CF152F">' + i.cut + '</span>元'
            }
          })
          item.cutMoney = cutMoney
          stringWord = '<div class="div-class">' + firstWord + '</div>'
          // list.push({
          //   type: 'text',
          //   text: firstWord
          // })
        } else {
          // arr.map((i, k) => {
          //   string = (k === arr.length - 1) ? `满<span>${i.full}</span>减<span>${i.cut}</span>` : `满<span>${i.full}</span>减<span>${i.cut}</span>;`
          //   // cache = {
          //   //   type: 'text',
          //   //   text: string
          //   // }
          //   // list.push(cache)
          //   stringWord += string
          // })
          if (arr.length > 0) {
            string = `购满<span style="color:#CF152F">${arr[0].full}</span>元可减<span style="color:#CF152F">${arr[0].cut}</span>元`
          }
          stringWord = string
          cutMoney = 0
          item.cutMoney = cutMoney
          stringWord = '<div class="div-class">' + stringWord + '</div>'
        }
        // const result = [{
        //   name: 'div',
        //   attrs: {
        //     class: 'div-class',
        //     style: 'line-height: 20px; height:20px; color: red; text-align:left; font-size:14px;text-overflow: ellipsis;\n' +
        //   '    overflow: hidden;\n' +
        //   '    white-space: nowrap;'
        //   },
        //   children: list
        // }]
        return stringWord
      }
    },

    allCartLength() {
      let length = 0
      this.cartList.forEach(element => {
        if (element.type !== 4) {
          element.shopping_item_list.forEach(item => {
            length++
          })
        }
      })
      return length
    },
    totalPrice() {
      let price = 0
      let cut = 0
      if (this.selectList.length) {
        this.selectList.forEach(element => {
          price += ((element.from_type === 9 ? element[this.getShowPrice(this.user_info)] : element.vip_price) * element.num)
        })
      }
      this.cartList.forEach(item => {
        if (item.cutMoney) { cut += item.cutMoney }
      })
      return Math.round((price - cut) * 100) / 100
    },
    selectListLength() {
      let length = 0
      if (this.selectList.length) {
        this.selectList.forEach(element => {
          length += element.num * 1
        })
      }
      return length
    },
    cartContentStyle() {
      if (this.cartList.length === 0) {
        let b = '0rpx'
        //  #ifdef MP-WEIXIN
        b = '100rpx'
        // #endif
        return b
      } else {
        let a = '0rpx'
        //  #ifdef MP-WEIXIN
        a = '200rpx'
        // #endif
        //  #ifdef H5
        a = '200rpx'
        // #endif
        return a
      }
    },
    classPage() {
      if (this.cartList.length > 0) {
        return 'page-container cart-page has'
      } else {
        return 'page-container cart-page'
      }
    }

  },
  created() {
  },
  mounted() {
  },
  onLoad() {
    this._getShowPrice()
    this._getRecommend()
    this.showBlur = true
  },
  onShow() {
    this._getData()
    if (this.$refs.likeGoodsList) {
      this.$refs.likeGoodsList.init()
    }
  },
  onHide() {
    this.selectList = []
  },
  onReachBottom: debounce(function() {
    console.log('onReachBottom')
    this.$refs.likeGoodsList.loadMore()
  }, 500),
  methods: {
    accSub(arg1, arg2) {
      var r1, r2, m
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2))
      // last modify by deeka
      // 动态控制精度长度
      // n = (r1 >= r2) ? r1 : r2
      return ((arg1 * m - arg2 * m) / m)
    },
    onPullDownRefresh() {
      this.refreshFlag = true
      this.selectList = []
      this._getData()
    },
    trimSize(a) {
      return a.trim()
    },
    toGoodsDetail(item) {
      toGoods(item, 'navigateTo', {
        preseat: '商品列表',
        firstseat: '购物车'
      })
    },
    swipeClick(e, item) {
      if (e.index === 1) {
        this.deleteCartArray([item])
      } else if (e.index === 0) {
        this.bookMarks(item)
      }
      // console.log('当前点击的是第' + e.index + '个按钮，点击内容是' + e.content.text)
    },
    change(open) {
      console.log('当前开启状态：' + open)
    },
    async _getData() {
      this.selectList = []
      const result = await this.$api.cartApi.getShoppingCart()
      if (result.data) {
        setTimeout(() => {
          uni.stopPullDownRefresh()
          this.refreshFlag = false
        }, 500)
        this.cartList = result.data.shopping_cart
        if (this.cartList.length) {
          this.cartList.forEach((pItem) => {
            if (pItem.remark && pItem.shopping_item_list[0] && pItem.shopping_item_list[0].from_type === 8) {
              this.needCoach = pItem.remark
            }
            if (pItem.shopping_item_list[0] && pItem.shopping_item_list[0].type === 3) {
              pItem.shopping_item_list[0].pic = pItem.shopping_item_list[0].pack_goods.pack_list[0].pic
              pItem.shopping_item_list[0].goods_id = pItem.shopping_item_list[0].pack_goods.pack_list[0].goods_id
              pItem.shopping_item_list[0].properties_name = pItem.shopping_item_list[0].pack_goods.pack_list[0].properties_name
              pItem.shopping_item_list[0].sku_code = pItem.shopping_item_list[0].pack_goods.pack_list[0].sku_code
              pItem.shopping_item_list[0].pack_goods.pack_list = []
            }
          })
        }
      }
    },
    async _getRecommend() {
      const res = await this.$api.homeApi.getSubjectTag({
        page_size: 10,
        page_no: 1,
        tag_name: '爆款',
        hideLoading: true
      })
      this.goodsList = res.data.goods_list
    },
    addToSelected(item, parItem) {
      if (parItem.type === 4) {
        return
      }
      const index = this.selectList.indexOf(item)
      if (index > -1) {
        if (parItem.full_cut_tag) {
          item.checked = false
        }
        this.selectList.splice(index, 1)
        return
      }
      if (parItem.full_cut_tag) {
        item.checked = true
      }
      this.selectList.push(item)
    },
    _getShowPrice() {
      const _this = this
      uni.getStorage({
        key: 'biXuanWorld',
        success: function(res) {
          _this.user_info = res.data
        }
      })
    },
    getShowPrice(value) {
      if (!value) {
        return 'vip_price'
      }
      let state = 'vip_price'
      switch (value.current_member_card_type) {
        case 0:
          state = 'vip_price'
          break
        case 1:
          state = 'vip_price'
          break
        case 2:
          state = 'region_price'
          break
        case 3:
          state = 'region_price'
          break
        default:
          break
      }
      return state
    },
    selectedAll() {
      if (this.selectList.length < this.allCartLength) {
        this.cartList.forEach(element => {
          if (element.type !== 4) {
            element.shopping_item_list.forEach(item => {
              if (this.selectList.indexOf(item) < 0) {
                item.checked = true
                this.selectList.push(item)
              }
            })
          }
        })
        return
      } else {
        this.cartList.map(element => {
          element.shopping_item_list.map(item => {
            item.checked = false
          })
        })
      }
      this.selectList = []
    },
    checkedImage() {
      if (this.allCartLength !== 0 && this.selectList.length === this.allCartLength) {
        return true
      } else {
        return false
      }
    },
    async cartNumChange(data, item) {
      const res = this.$api.cartApi.updateShoppingCart({
        goods_id: item.goods_id,
        goods_type: item.type,
        sku_code: item.sku_code,
        num: data,
        hideLoading: true
      })
      if (res.code) return
      if (item.type === 3) {
        this.$set(item, 'num', data)
        setTimeout(() => {
          this._getData()
        }, 100)
      } else {
        this.$set(item, 'num', data)
      }
    },
    async deleteCartArray(deleteArray) {
      if (!deleteArray.length) {
        uni.showToast({
          title: '请选删除商品',
          icon: 'none',
          duration: 2 * 1000
        })
        return
      }
      const array = []
      deleteArray.forEach(item => {
        const data = {
          goods_id: item.goods_id,
          goods_type: item.type,
          sku_code: item.sku_code
        }
        if (item.type * 1 === 2) {
          data.pack = []
          item.pack_goods.pack_list.forEach(item => {
            data.pack.push({ 'sku_code': item.sku_code })
          })
          data.pack_type = item.pack_type
        }
        array.push(data)
      })
      const res = await this.$api.cartApi.deleteShoppingCart({
        shopping_cart_items: JSON.stringify(array)
      })
      if (res.code) return
      uni.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2 * 1000
      })
      this._getData()
    },
    async bookMarks(item) {
      const data = {
        goods_id: item.goods_id,
        goods_type: item.type,
        sku_code: item.sku_code
      }
      if (item.type * 1 === 2) {
        data.pack = []
        item.pack_goods.pack_list.forEach(item => {
          data.pack.push({ 'sku_code': item.sku_code })
        })
        data.pack_type = item.pack_type
      }
      const res = await this.$api.cartApi.deleteShoppingCart({
        shopping_cart_items: JSON.stringify([data]),
        bookmarks_goods_id: item.goods_id,
        bookmarks_goods_type: item.type
      })
      if (res.code) return
      uni.showToast({
        title: '成功移入收藏夹, 可在我的收藏中查看',
        icon: 'none',
        duration: 2 * 1000
      })
      this._getData()
    },
    async toOrderCheck() {
      if (this.needCoach) {
        let count = 0
        this.selectList.forEach(item => {
          if (item.from_type === 8) {
            count += item.vip_price * item.num
          }
        })
        if (this.needCoach > count) {
          uni.showToast({
            title: '买满' + this.needCoach + '元即可升级大区会员',
            icon: 'none',
            duration: 2 * 1000
          })
          // this.$vux.toast.text('买满' + this.needCoach + '元即可升级大区会员')
          return
        }
      }
      if (!this.selectList.length) {
        uni.showToast({
          title: '请选择结算商品',
          icon: 'none',
          duration: 2 * 1000
        })
        // this.$vux.toast.text('请选择结算商品')
        return
      }
      // this.$vux.loading.show({
      //   text: '加载中'
      // })
      const array = []
      //   // 如果 有checked字段 则 是满减
      // let FullCutNum = 0
      // this.selectList.map(item => {
      //   if (item.checked) { FullCutNum += 1 }
      // })
      // if (FullCutNum) { this.hasFullCut = true }
      this.selectList.forEach(item => {
        const temp = {
          goods_id: item.goods_id,
          goods_type: item.type * 1 === 0 ? '1' : item.type,
          sku_code: '',
          activity_id: item.activity_id,
          pack_list: [],
          pack_type: item.pack_type * 1 === 0 ? '2' : item.pack_type,
          present_list: [],
          num: item.num,
          from_type: item.from_type * 1 === 0 ? '1' : (item.full_cut_id ? 24 : item.from_type) // 满减的要写24
        }
        if (item.type === 2) {
          item.pack_goods.pack_list.forEach(element => {
            // if (this.hasFullCut) { element.from_type = 24 }
            temp.pack_list.push({
              sku_code: element.sku_code,
              num: element.package_goods_number,
              activity_id: element.activity_id,
              from_type: element.from_type
            })
          })
        } else {
          temp.sku_code = item.sku_code
        }
        // 满减修改fromType
        // if (this.hasFullCut) {
        //   temp.from_type = 24
        // }
        if (item.pack_goods && item.pack_goods.present_list && item.pack_goods.present_list.length) {
          const presentSku = []
          item.pack_goods.present_list.forEach(element => {
            // if (this.hasFullCut) { element.from_type = 24 }
            presentSku.push({
              sku_code: element.sku_code,
              num: element.package_goods_number,
              activity_id: element.activity_id,
              from_type: element.from_type
            })
          })
          temp.present_list = presentSku
        }
        array.push(temp)
      })
      const data = JSON.stringify(array)
      const res = await this.$api.orderApi.orderSettle({
        is_used_coupon: 1,
        shopping_list: data
      })
      // this.$vux.loading.hide()
      this.$store.dispatch('setGoodsTemp', {
        shopping_list: data,
        data: res.data
      })
      // this.setGoodsTemp({
      //   shopping_list: data,
      //   data: res.data
      // })
      if (res.code) {
        return
      }
      uni.setStorageSync('preseat', '购物车')
      uni.setStorageSync('firstseat', '购物车')
      this.$navigateTo('/pagesOrder/orderCheck/index')
    },
    deleteAll() {
      this.$refs.confirm.show({
        title: '提醒',
        content: '是否确认全部清空',
        yesCb: async() => {
          const tempAry = []
          this.cartList.forEach(element => {
            if (element.type === 4) {
              element.shopping_item_list.forEach(item => {
                tempAry.push(item)
              })
            }
          })
          this.deleteCartArray(tempAry)
        }
      })
    },
    // 替换满减中的数字加标签
    // replaceHtmlNum(item) {
    //   const arr = item.full_cut_list
    //   const list = []
    //   let cache = {}
    //   let string = ''
    //   arr.map(async(i, k) => {
    //     string = (k === arr.length - 1) ? `满${i.full}减${i.cut}` : `满${i.full}减${i.cut};`
    //     cache = {
    //       type: 'text',
    //       text: string
    //     }
    //     list.push(cache)
    //   })
    //   const result = [{
    //     name: 'div',
    //     attrs: {
    //       class: 'div-class',
    //       style: 'line-height: 20px; height:20px; color: red; text-align:left; font-size:14px;text-overflow: ellipsis;\n' +
    //       '    overflow: hidden;\n' +
    //       '    white-space: nowrap;'
    //     },
    //     children: list
    //   }]
    //   return result
    //
    //   //       若金额79，79<99，则提示：购满99，可减9元，还差20元
    //
    //   // 金额为129,99≤129<199,则提示：购满99，已减9元，满199可减19元
    //
    //   // 金额为209，199≤209，则提示：购满199，已减19元
    //
    //   // if (!str) return ''
    //   // const arr = str.match(/\d+/g)
    //   // const arr1 = []
    //   // if (arr && arr.length > 0) {
    //   //   arr.forEach(i => {
    //   //     const index = str.indexOf(i)
    //   //     if (index > -1) {
    //   //       str = str.replace(i, 'p' + index)
    //   //     }
    //   //     arr1.push({
    //   //       value: `<span style="color: #e21536">${i}</span>`,
    //   //       label: 'p' + index
    //   //     })
    //   //   })
    //   // }
    //   // arr1.forEach(i => {
    //   //   str = str.replace(i.label, i.value)
    //   // })
    //   // return ''
    // },
    // 去满减专题页
    lookFullCutShop(item) {
      this.$navigateTo('/pagesDetail/fullcut/index?id=' + item.full_cut_id + '&from=cart')
    }
  }
}
</script>

